package com.storage.mongo;


import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

import org.bson.types.ObjectId;


import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class DiscussionForum {

	
	Morphia morp;
	Mongo m; 
	DB db; 
	DBCollection topicColl; 
	Datastore ds;
	
	@SuppressWarnings("deprecation")
	DiscussionForum() throws UnknownHostException, MongoException
	{
		morp = new Morphia();
		m = new Mongo( "localhost" , 27017 );
		//drop db
		//m.dropDatabase("mydb");
		db = m.getDB("mydb");
		morp.map(ETopic.class).map(EComments.class);
		ds = morp.createDatastore("mydb");
	}
	
	
	
	public void getallrecords()
	{

		List<ETopic> lt = ds.find(ETopic.class).asList();
		
		for(ETopic t1 : lt)
		{
			System.out.print(t1.getId());
			System.out.print(t1.getTopicTitle());
			System.out.print(t1.getTopicContent());
			System.out.print(t1.getCommunityID());
			System.out.print(t1.getCreatedDate());
			System.out.print(t1.getCreatedUser());
			System.out.print(t1.getComments().getCreatedBy());
			System.out.println(t1.getComments().getCreatedText());
		}
	}
	
	public void createTopic(String topicTitle,String topicContent,String createdUser,String communityID) throws UnknownHostException, MongoException 
	{

		ETopic t = new ETopic(new EComments());
		
		t.setTopicTitle(topicTitle);
		t.setTopicContent(topicContent);
		t.setCommunityID(communityID);
		t.setCreatedUser(createdUser);
		t.setCreatedDate(new Date().toString());
		
		ds.save(t);
		System.out.println("Topic created successfully");
		
	}
	
	public void addComments(String topicName,String commentBy,String commentText) throws UnknownHostException, MongoException
	{

		ETopic t = new ETopic(new EComments(commentBy,commentText,new Date().toString()));
		t.setTopicTitle(topicName);

		ds.save(t);
		System.out.println("Comments added successfully");
	}
	
	public Query<ETopic> getTopics()
	{

		Query<ETopic> query =  ds.find(ETopic.class).field("topicContent").exists();
		for (ETopic t : query)
		{
			System.out.println(t.getTopicTitle());
		}
		return query;
		
	}
	
	
	public Query<ETopic> getComments(String topicTitle)
	{
		
		Query<ETopic> query= ds.createQuery(ETopic.class).field("topicTitle").equal(topicTitle);
		for (ETopic t : query)
		{
			System.out.println(t.getComments().getCreatedText());
		}
		return query;
		
		
	}
	

}
